package com.atguigu.spzx.common.handler;

import com.atguigu.spzx.common.consts.SpzxConsts;
import com.atguigu.spzx.common.util.AuthUtil;
import com.atguigu.spzx.model.entity.user.UserInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
//如果请求路径满足 /api/**/auth/**  根据请求头token获取登录状态透传给后续的业务
@Component
public class SpzxAuthInterceptor implements HandlerInterceptor {
    @Resource
    RedisTemplate redisTemplate;
    AntPathMatcher matcher = new AntPathMatcher();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        String path = request.getRequestURI();
//        boolean match = matcher.match("/api/**/auth/**", path);
//        if(!match){
//            //请求访问的是不需要登录的资源
//            return true;
//        }
        //请求访问的是需要登录的资源：登录状态在网关中已经校验了
        String token = request.getHeader("token");
        UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(SpzxConsts.SPZX_USER_LOGIN_PREFIX + token);
        AuthUtil.setUserInfo(userInfo);
        //放行请求
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       AuthUtil.removeUserInfo();
    }
}
